using CoreManager.AI.Models;
using CoreManager.AI.Services;
using CoreManager.API.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using System.Text.Json;

namespace CoreManager.API.System.Controllers;

/// <summary>
/// AI 聊天控制器
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class AIController : BaseController
{
    private readonly IAIService _aiService;
    private readonly ILogger<AIController> _logger;

    public AIController(
        IAIService aiService,
        ILogger<AIController> logger) : base(logger)
    {
        _aiService = aiService;
        _logger = logger;
    }

    /// <summary>
    /// 流式聊天（SSE）
    /// </summary>
    /// <param name="request">聊天请求</param>
    /// <param name="cancellationToken">取消令牌</param>
    [HttpPost("chat/stream")]
    [AllowAnonymous]
    public async Task StreamChat(
        [FromBody] ChatRequest request,
        CancellationToken cancellationToken)
    {
        Response.Headers.Append("Content-Type", "text/event-stream");
        Response.Headers.Append("Cache-Control", "no-cache");
        Response.Headers.Append("Connection", "keep-alive");
        Response.Headers.Append("X-Accel-Buffering", "no");

        try
        {
            _logger.LogInformation("收到流式聊天请求: {Message}", request.Message);

            await foreach (var response in _aiService.StreamChatAsync(request, cancellationToken))
            {
                // SSE 格式: data: {json}\n\n
                var json = JsonSerializer.Serialize(response);
                var sseMessage = $"data: {json}\n\n";
                var bytes = Encoding.UTF8.GetBytes(sseMessage);

                await Response.Body.WriteAsync(bytes, cancellationToken);
                await Response.Body.FlushAsync(cancellationToken);

                if (response.IsComplete)
                {
                    break;
                }
            }

            _logger.LogInformation("流式聊天完成");
        }
        catch (OperationCanceledException)
        {
            _logger.LogWarning("流式聊天被取消");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "流式聊天失败");
            
            var errorResponse = new ChatResponse
            {
                Message = $"服务器错误: {ex.Message}",
                IsComplete = true
            };
            
            var json = JsonSerializer.Serialize(errorResponse);
            var sseMessage = $"data: {json}\n\n";
            var bytes = Encoding.UTF8.GetBytes(sseMessage);
            
            await Response.Body.WriteAsync(bytes, cancellationToken);
            await Response.Body.FlushAsync(cancellationToken);
        }
    }

    /// <summary>
    /// 获取可用的模型列表
    /// </summary>
    [HttpGet("models")]
    [AllowAnonymous]
    public async Task<IActionResult> GetModels()
    {
        try
        {
            var models = await _aiService.GetAvailableModelsAsync();
            return Success(models);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取模型列表失败");
            return Fail("获取模型列表失败");
        }
    }

    /// <summary>
    /// 健康检查
    /// </summary>
    [HttpGet("health")]
    [AllowAnonymous]
    public IActionResult Health()
    {
        return Success(new { status = "healthy", timestamp = DateTime.UtcNow });
    }
}

